<script src="../../common/js/quill-config.js"></script>
<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input  v-model="keyword" placeholder="请输入关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="keywordQuery">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="success" @click="onsale">上架</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="danger" @click="offsale">下架</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
    <el-table :data="products" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="服务名称" width="120">
      </el-table-column>
      <el-table-column prop="costprice" label="成本价" width="120">
      </el-table-column>
      <el-table-column prop="saleprice" label="销售价" width="120">
      </el-table-column>
      <el-table-column prop="salecount" label="销量" width="120">
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template scope="scope">
          <span v-if="scope.row.state==1" style="color: green">上架</span>
          <span v-else style="color: red">下架</span>
        </template>
      </el-table-column>
      <el-table-column prop="offsaletime" label="下架时间" width="120">
      </el-table-column>
      <el-table-column prop="onsaletime" label="上架时间" width="120">
      </el-table-column>
      <el-table-column prop="createtime" label="创建时间" width="120">
      </el-table-column>


      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>


    </el-table>

		<!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :page-size="pageSize"
                     :current-page="currentPage"
                     :total="totals"
                     style="float:right;">
      </el-pagination>
    </el-col>

		<!--编辑界面-->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="服务名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="成本价" prop="costprice">
          <el-input v-model="saveForm.costprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="市场价" prop="saleprice">
          <el-input v-model="saveForm.saleprice" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="服务资源">
          <el-upload class="upload-demo"
                     action="http://localhost:8080/fastDfs/"
                     :on-remove="handleRemove"
                     :on-success="handleSuccess"
                     :file-list="fileList"
                     list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>



        <el-form-item label="简介" prop="intro">
          <!-- v-if="saveForm.productDetail" 修改v-model绑定对象报错问题，v-if对需要显示的数据判断下 -->
          <quill-editor  v-model="saveForm.productDetail.intro" v-if="saveForm.productDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>
        <el-form-item label="服务须知" prop="orderNotice" >
          <quill-editor  v-model="saveForm.productDetail.adoptNotice" v-if="saveForm.productDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>


	</section>
</template>

<script>
//引入Vue的ueditor的资源
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import quillConfig from '../../common/js/quill-config';


export default {
    components: {
      quillEditor
    },
		data() {
			return {
        quillOption: quillConfig,
        products: [],
        //店铺
        shops:[],
        //服务类型数
        productTypeTree:[],
        currentPage: 1,/*当前页*/
        pageSize: 5,/*每页显示条数*/
        totals: 0, /*总条数*/

        //关键字查询
        keyword:'',
        //列表选中列
        sels: [],


				filters: {
					name: ''
				},

				total: 0,
				page: 1,
				listLoading: false,



        title:'',//标题
        saveFormVisible: false,//添加和修改对话框是否显示
        saveLoading: false,  //保存的忙等框 - 在提交按钮上
        saveFormRules: {     //表单项验证规则
          name: [
            { required: true, message: '请输入服务名称', trigger: 'blur' }
          ]
        },
        //对话框数据：建议字符串用''，id用null
        saveForm: {
          id: null,
          name: '',
          costprice: 0,
          saleprice: 0,
          typeId: null,
          resources: '',
          state: 0, //默认下架 - 前台看不见这个服务 - 审核之后才能上架
          productDetail:{
            productId: null,
            intro: '',
            adoptNotice: ''
          }
        },
        fileList:[]
			}

		},
		methods: {


      //1.获取服务列表
      getProducts() {
        let para = {
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.keyword
        };

        this.listLoading = true; //开启忙等框
        this.$http.post("/product",para).then(res=>{

          this.products=res.data.data;
          this.totals=res.data.totals;
          this.listLoading = false; //关闭忙等框

        }).catch(res=>{
          this.$message.error("系统繁忙，请稍后重试!!!")
        })
      },

      //高级查询
      keywordQuery(){
        this.currentPage = 1;
        this.getProducts();
      },


			//性别显示转换
			formatSex: function (row, column) {
				return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
			},
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getProducts();
			},

			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					this.$http.delete("/product/"+row.id).then(res=>{
					  if(res.data.success){
					    let totalPage =  Math.ceil(this.totals/this.pageSize);
					    //如果当前页是最后一页(总页数) 而且是最后一条数据，并且不是第一页就 让当前页等于当前页减1
					    if (this.currentPage == totalPage && (this.totals - 1)%this.pageSize == 0 && this.currentPage!=1){
					      this.currentPage = this.currentPage-1;
              }
					    this.getProducts()
            }else {
					    this.$massage.error("骚瑞，系统繁忙【500】")
            }
            this.listLoading = false;
          }).catch(res=>{
            this.$massage.error("骚瑞，系统繁忙【400/404】")
          })
				}).catch(() => {

				});
			},


      selsChange: function (sels) {
        this.sels = sels;
      },
      //批量删除
      batchRemove: function () {
        var ids = this.sels.map(item => item.id);
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
         this.$http.patch("/product/",ids).then(res=>{
           if (res.data.success){
             this.currentPage = 1,
                 this.getProducts()
           }else {
             this.$massage.error("骚瑞，系统繁忙【500】")
           }
           this.listLoading = false;
         }).catch(res=>{
           this.$massage.error("骚瑞，系统繁忙【400/404】")
         })
        }).catch(() => {

        });
      },

			//显示编辑界面
			handleEdit: function (index, row) {
        this.title = '编辑';
        this.saveFormVisible = true;
        this.saveForm = Object.assign({}, row);

        //清空fileList的数据
        this.fileList = [];
        if (this.saveForm.resources){
          let paths = this.saveForm.resources.split(",");
          for (var i = 0;i<paths.length;i++){
            this.fileList.push({"url":"http://123.207.27.208"+paths[i]});
          }
        }

			},

      //点击新增按钮弹出对话框
      handleAdd: function () {
        this.title = "新增";
        this.saveForm = {
          id: null,
          name: '',
          costprice: 0,
          saleprice: 0,
          resources: '',
          state: 0, //默认下架 - 前台看不见这个服务 - 审核之后才能上架
          productDetail:{
            productId: null,
            intro: '',
            adoptNotice: ''
          }
        };
        //清空fileList的数据
        this.fileList = [];
        //弹出对话框
        this.saveFormVisible = true;
      },
			//添加编辑
			saveSubmit: function () {
				this.$refs.saveForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.saveLoading = true;
              // let result = this.saveForm.typeId;
              // //如果为null,[] 就赋值为null，后端Long可以接收为null
              // if(result==null ||  result.length==0 ){
              //   this.saveForm.typeId = null;
              // }
              // //如果有值：[ 1 ],[ 2, 5, 6 ]  或直接一个数字
              // if(result.length){ //没有选过就是之前的部门的话，result.length为undefined，判断为false
              //   this.saveForm.typeId = result[result.length-1];
              // }else{
              //   //没有选过
              //   this.saveForm.typeId = result;
              // }

              this.$http.put("/product",this.saveForm).then(res=>{
                if (res.data.success){
                  this.getProducts();
                }else {
                  this.$massage.error("骚瑞，系统繁忙【500】")
                }
                this.saveLoading = false;
              }).catch(res=>{
                this.$massage.error("骚瑞，系统繁忙【400/404】")
                this.saveLoading = false;
              })
						});
            this.saveFormVisible = false;
					}
				});
			},

      //点击删除图片时的处理
      handleRemove(file,fileList){
        let filePath = file.url.substring(file.url.indexOf("/group1"));
        //1.调用删除组接口删除文件
        this.$http.delete("/fastDfs?path="+filePath).then(res=>{
          if (res.data.success){
            this.$message.success("删除成功");
          }else {
            this.$message.error("删除失败");
          }
        }).catch(res=>{
          this.$message.error("系统繁忙");
        })

        //2.对resource的处理
        if (this.saveForm.resources){
          let paths = this.saveForm.resources.split(",");
          for (var i = 0;i<paths.length;i++){
            if (filePath==paths[i]){
              paths.splice(i,1)
            }
            break;
          }
          this.saveForm.resources = paths.join(",");
        }

        //3.对filelist的处理
        this.fileList = [];
        if (this.saveForm.resources){
          let paths = this.saveForm.resources.split(",");
          for (var i = 0;i<paths.length;i++){
            this.fileList.push({"url":"http://123.207.27.208"+paths[i]});
          }
        }
      },


      //图片上传成功的回调处理  resource filelist
      handleSuccess(response,file,fileList){
        let filePath = response.resultObj;
        //1.对resource的处理
        if (this.saveForm.resources){
          this.saveForm.resources = this.saveForm.resources+","+filePath;
        }else {
          this.saveForm.resources = filePath;
        }
        //2.对fileList的处理
        this.fileList = [];
        if (this.saveForm.resources){
          let paths = this.saveForm.resources.split(",");
          for (var i = 0;i<paths.length;i++){
            this.fileList.push({"url":"http://123.207.27.208"+paths[i]});
          }
        }
      },


      //服务上架
      onsale(){
        var ids = this.sels.map(item => item.id);
        if (!ids ||ids.length ==0){
          this.$message.error("请选中再上架");
          return ;
        }
        this.$http.post("/product/onsale",ids).then(res=>{
          if (res.data.success){
            this.getProducts();
          }else {
            this.$message.error(res.data.msg);
          }
        }).catch(res=>{
          this.$message.error("系统异常 400/404")
        })
      },

      //服务下架
      offsale(){
        var ids = this.sels.map(item => item.id);
        if (!ids ||ids.length ==0){
          this.$message.error("请选中再下架");
          return ;
        }
        this.$http.post("/product/offsale",ids).then(res=>{
          if (res.data.success){
            this.getProducts();
          }else {
            this.$message.error("下架失败")
          }
        }).catch(res=>{
          this.$message.error("系统异常 400/404")
        })
      }
		},



		mounted() {
			this.getProducts();
		}
	}

</script>

<style scoped>

</style>